package com.jy.appmarket.service;

import java.util.List;
import java.util.Set;

import com.jy.appmarket.utils.BadgeUtils;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.Settings;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;


/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2015年1月6日
 * @version 1.0
 */

public class DaemonService extends Service {
	private static final String TAG = "DaemonService";
	private ScanThread mScanThread;
	public static Object sLock = new Object();

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (!BadgeUtils.isSupportBadge()) {
			LogUtil.d(TAG, "not supported");
			stopSelf();
			return super.onStartCommand(intent, flags, startId);
		}
		startScan();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		mScanThread = null;
		// LogUtil.d(TAG, "onDestroy");
		super.onDestroy();
	}

	private void startScan() {
		// LogUtil.d(TAG, "enter startScan");
		if (mScanThread == null) {
			mScanThread = new ScanThread();
			LogUtil.d(TAG, "start thread");
			mScanThread.start();
		}
	}

	private class ScanThread extends Thread {
		@Override
		public void run() {
			while (true) {
				// LogUtil.d(TAG, "begin scan");
				synchronized (sLock) {
					Set<String> apps = Settings.getBadgePkgs(DaemonService.this);
					if (apps == null || apps.size() == 0) {
						break;
					}
					ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
					@SuppressWarnings("deprecation")
					List<RunningTaskInfo> tasks = am.getRunningTasks(10);
					for (int i = 0; i < tasks.size(); i++) {
						RunningTaskInfo rti = tasks.get(i);
						String pkg = rti.baseActivity.getPackageName();
						if (apps.contains(pkg)) {
							LogUtil.d(TAG, "found:" + pkg);
							String cls = BadgeUtils.getLaunchClass(DaemonService.this, pkg);
							BadgeUtils.clearBadge(DaemonService.this, pkg, cls);
							apps.remove(pkg);
						}
					}
					Settings.setBadgePkgs(DaemonService.this, apps);
				}
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			LogUtil.d(TAG, "scan finished");
			stopSelf();
		}
	}
}
